package common

import (
	fileModel "blog/app/model/file"
	"blog/core"

	"golang.org/x/exp/slices"
)

type cache struct {
}

var Cache = new(cache)

func (c cache) File(hash string) string {
	key := "fileAll_" + hash
	if !core.Redis.GetString().Exists(key) {
		var fileInfo fileModel.File
		var configInfo fileModel.Config
		if core.DbConnect.Model(&fileModel.File{}).Where("hash = ?", hash).Find(&fileInfo).RowsAffected == 0 {
			return ""
		}
		if core.DbConnect.Model(&fileModel.Config{}).Where("id = ?", fileInfo.Fid).Find(&configInfo).RowsAffected == 0 {
			return ""
		}

		url := "http://"
		if configInfo.IsHttps == 1 {
			url = "https://"
		}

		url = url + configInfo.Domain + "/" + fileInfo.Url
		core.Redis.GetString().SetEx(key, url, 3600)
	}
	return core.Redis.GetString().Get(key)
}

func (c cache) Files(hash []string) map[string]string {
	var h = make(map[string]string)
	var notCache = make([]string, 0)

	for _, v := range hash {
		key := "fileAll_" + v
		if core.Redis.GetString().Exists(key) {
			h[v] = core.Redis.GetString().Get(key)
		} else {
			notCache = append(notCache, v)
		}
	}

	if len(notCache) == 0 {
		return h
	}

	var config = make(map[int]fileModel.Config)
	var ll []fileModel.File
	cc := make([]fileModel.Config, 0)
	core.DbConnect.Model(&fileModel.File{}).Where("`hash` in (?)", notCache).Find(&ll)
	configIds := make([]int, 0)
	for _, v := range ll {
		if slices.Contains(configIds, v.Fid) {
			continue
		}
		configIds = append(configIds, v.Fid)
	}

	core.DbConnect.Model(&fileModel.Config{}).Where("id in (?)", configIds).Find(&cc)
	for _, v := range cc {
		config[v.ID] = v
	}

	for _, v := range ll {
		key := "fileAll_" + v.Hash
		if configInfo, ok := config[v.Fid]; ok && slices.Contains(hash, v.Hash) {
			url := "http://"
			if configInfo.IsHttps == 1 {
				url = "https://"
			}
			url = url + configInfo.Domain + "/" + v.Url
			core.Redis.GetString().SetEx(key, url, 3600)
			h[v.Hash] = url
		} else {
			h[v.Hash] = ""
		}
	}
	return h
}

func (c cache) FileSet(hash, url string) {
	key := "fileAll_" + hash
	core.Redis.GetString().SetEx(key, url, 3600)
}

func (c cache) ConfigGet(group string, key string) {
	// core.Redis.GetHash()
}
